package com.roadjava.demo11.advice;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@ControllerAdvice
public class RoadJavaControllerAdvice11 {

    // @Validated 注解写在类上的时候会报这个错误
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public List<String> handleEx(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> set = e.getConstraintViolations();
        List<String> list = set.stream().map(v ->
                        "属性：" + v.getPropertyPath()
                                + "，属性的值：" + v.getInvalidValue()
                                + "，校验不通过的提示信息：" + v.getMessage())
                .collect(Collectors.toList());
        return list;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleEx(Exception e) {
        return e.getMessage();
    }

}